package com.sws.interceptor;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;
import com.sws.Constant;
import com.sws.utils.EhCache;

public class PermissionInterceptor extends HandlerInterceptorAdapter {
	
	private Logger logger = LoggerFactory.getLogger(PermissionInterceptor.class);

	@SuppressWarnings("unchecked")
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// TODO Auto-generated method stub
		//获取请求路径
		boolean isAllow = false;
		response.setContentType("text/html;utf-8");
		response.setCharacterEncoding("utf-8");
		Integer userId = (Integer)request.getSession().getAttribute("userId");
		if (userId != null) {
			List list = (List<String>)EhCache.getInstance().get((int)userId);
			if (list != null && list.contains(request.getServletPath())) {
				isAllow = true;
			}
		}
		
		if(!isAllow) {
			JSONObject result = new JSONObject();
			result.put("status", Constant.INSTANSE.NOT_PERMISSION);
			result.put("msg", "没有权限！");
			result.put("time", new Date());
			response.getWriter().write(result.toJSONString());
		}
		return isAllow;
	}
}
